package com.jh.netty.opaqueopacimeter;

import com.jh.netty.client.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;


public class TcpClient {
    public static void main(String[] args) throws Exception {
        //1.创建一个 EventLoopGroup 线程组
        NioEventLoopGroup group = new NioEventLoopGroup();
        //2.创建客户端启动助手
        Bootstrap b = new Bootstrap();
        b.group(group) //3.设置 EventLoopGroup 线程组
                .option(ChannelOption.TCP_NODELAY, true)//屏蔽Nagle算法试图
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .channel(NioSocketChannel.class) //4.使用 NioSocketChannel 作为客户端通道实现
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

//                        ch.pipeline().addLast(new NettyClientHandler());
                        ch.pipeline().addLast(
                                "lengthDecoder",
                                new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 4, 2, 0, 0)
                        );
                        ch.pipeline().addLast("decoder", new HexStringDecoder());
                        ch.pipeline().addLast("encoder", new HexStringEncoder());

                        

                    }
                    //5.创建一个通道初始化对象
//        @Override
//        protected void initChannel(SocketChannel sc) { //6.往 Pipeline 链中添加自定义的业务
////        处 理 handler
//        sc.pipeline().addLast(new NettyClientHandler()); //客户端业务处理类System.out.println("......Client is ready.......");
//        }
                });
        //7.启动客户端,等待连接上服务器端(非阻塞) ChannelFuture cf = b.connect("127.0.0.1", 9999).sync();
        //8.等待连接关闭(非阻塞) cf.channel().closeFuture().sync();
    }
}